package com.xyzwps.webfluxjava.common.exception;

import com.alibaba.fastjson.JSONObject;
import lombok.val;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.Map;

/**
 * TODO: 如何自定义 {@link org.springframework.web.server.WebExceptionHandler}
 *
 * 自定义一个组织 Functional Endpoints 抛出的异常信息的 {@link ErrorAttributes}。
 */
public class MyErrorAttributes implements ErrorAttributes {

    // TODO: 这个东西能不能改？
    private static final String ERROR_ATTRIBUTE = DefaultErrorAttributes.class.getName() + ".ERROR";

    private final boolean includeException;

    /**
     * Create a new {@link DefaultErrorAttributes} instance.
     *
     * @param includeException whether to include the "exception" attribute
     */
    public MyErrorAttributes(boolean includeException) {
        this.includeException = includeException;
    }

    /**
     * 返回结果中，必须要有 {@code status} 这一项，见 {@link DefaultErrorWebExceptionHandler#getHttpStatus}
     */
    @Override
    public Map<String, Object> getErrorAttributes(ServerRequest request,
                                                  boolean includeStackTrace) {
        val errorAttributes = new JSONObject();
        errorAttributes.put("routerType", "functional");
        errorAttributes.put("timestamp", new Date());
        errorAttributes.put("path", request.path());
        Throwable error = getError(request);
        HttpStatus errorStatus = determineHttpStatus(error);
        errorAttributes.put("status", errorStatus.value());
        errorAttributes.put("message", error.getMessage());
        handleException(errorAttributes, error, includeStackTrace);
        return errorAttributes;
    }

    private HttpStatus determineHttpStatus(Throwable error) {
        if (error instanceof BizException) {
            return ((BizException) error).getStatus();
        }
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }

    private void addStackTrace(Map<String, Object> errorAttributes, Throwable error) {
        StringWriter stackTrace = new StringWriter();
        error.printStackTrace(new PrintWriter(stackTrace));
        stackTrace.flush();
        errorAttributes.put("trace", stackTrace.toString());
    }

    private void handleException(Map<String, Object> errorAttributes, Throwable error,
                                 boolean includeStackTrace) {
        if (this.includeException) {
            errorAttributes.put("exception", error.getClass().getName());
            val cause = error.getCause();
            if (cause != null) {
                errorAttributes.put("cause", cause.getClass().getName());
            }
        }
        if (includeStackTrace) {
            addStackTrace(errorAttributes, error);
        }
        if (error instanceof BindingResult) {
            BindingResult result = (BindingResult) error;
            if (result.getErrorCount() > 0) {
                errorAttributes.put("errors", result.getAllErrors());
            }
        }
    }

    @Override
    public Throwable getError(ServerRequest request) {
        return (Throwable) request.attribute(ERROR_ATTRIBUTE)
                .orElseThrow(() -> new IllegalStateException("Missing exception attribute in ServerWebExchange"));
    }

    @Override
    public void storeErrorInformation(Throwable error, ServerWebExchange exchange) {
        exchange.getAttributes().putIfAbsent(ERROR_ATTRIBUTE, error);
    }

}
